<?php

class SetImageAction extends CAction
{
    private $_kitchen;
    private $_succ = false;

    private function renderView()
    {
        $this->controller->layout='simple';
        $this->controller->render('setImage',array('kitchen'=>$this->_kitchen, 'succ'=>$this->_succ));
    }

    private function validateImage()
    {
        if($this->_kitchen->image===null) {
            $this->_kitchen->addError('image','图片不能为空');
            return false;            
        }            
        if(!file_exists($this->_kitchen->image->getTempName())) {
            $this->_kitchen->addError('image','文件大小超过限制');
            return false;            
        }
        if(!UserImage::validateUploadFormat('kitchen', $this->_kitchen->image->getExtensionName())) {
            $this->_kitchen->addError('image','文件格式不正确');
            return false;
        }
        return true;
    }    
    
    public function run()
    {
        if(!isset($_GET['id']))    
            throw new CHttpException(400,'the request is invalid');

        if($_GET['id']!=Yii::app()->user->id)
            throw new CHttpException(403,'cannot edit the kitchen not belong to you');
    
        $this->_kitchen = new Kitchen;
        $this->_kitchen->id = $_GET['id'];        
        if(!isset($_POST['Kitchen'])) {
            $this->renderView();
            return;
        }

        $this->_kitchen->attributes=$_POST['Kitchen'];
        $this->_kitchen->image=CUploadedFile::getInstance($this->_kitchen,'image');
        if(!$this->validateImage()) {
            $this->renderView();
            return;        
        }

        // lazy loading for kitchen
        $image = $this->_kitchen->image;        
        $this->_kitchen=Kitchen::loadObjectById($_GET['id']);
        if($this->_kitchen===null)
            throw new CHttpException(404,'The requested kitchen does not exist.');
        if($this->_kitchen->id!=Yii::app()->user->id)
            throw new CHttpException(403,'cannot edit the kitchen not belong to you');
        
        $image=UserImage::create('kitchen', $image->getTempName());
        if($image===false){
            $this->_kitchen->addError('image','保存文件失败');
            $this->renderView();
            return;        
        }

        $oldImage=$this->_kitchen->image;
        $this->_kitchen->image=$image;
        if(!Kitchen::saveObject($this->_kitchen, array('image','updateTime'))) {
            UserImage::delete('kitchen',$this->_kitchen->image);
        }
        else {
            UserImage::delete('kitchen', $oldImage);                        
            $this->_succ=true;
        }
        
        $this->renderView();
    }
}
  
?>